//
//  AlertService.m
//  YouthOlympic2014
//
//  Created by xiangpaopao on 14-7-9.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "AlertService.h"
#import "NSDate+NSDateAddition.h"
#import "GameEvent.h"
#import "CalendarMarkService.h"


NSString * AlertDidChangedNotification = @"AlertDidChangedNotification";

#define kUserDefaultsEventAlert @"kUserDefaultsEventAlert"
#define kUserDefaultsDailyAlert @"kUserDefaultsDailyAlert"
#define kUserDefaultsEventVal @"kUserDefaultsEventVal"
#define kUserDefaultsDailyVal @"kUserDefaultsDailyVal"

static AlertService* alertCenter = nil;

@interface AlertService()

@property (nonatomic, strong) NSArray*  eventsArray;

@end

@implementation AlertService

+ (id)sharedCenter{
    if (nil == alertCenter) {
        alertCenter = [[AlertService alloc] init];
    }
    return alertCenter;
}

- (id)init
{
    self = [super init];
    if (self) {
        if (![[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsEventAlert]) {
            NSNumber* isOn = [NSNumber numberWithBool:YES];
            [[NSUserDefaults standardUserDefaults] setObject:isOn
                                                      forKey:kUserDefaultsEventAlert];
        }
        if (![[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsDailyAlert]) {
            NSNumber* isOn = [NSNumber numberWithBool:YES];
            [[NSUserDefaults standardUserDefaults] setObject:isOn
                                                      forKey:kUserDefaultsDailyAlert];
        }
        //
        if (![[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsEventVal]) {
            NSString* val = @"30";
            [[NSUserDefaults standardUserDefaults] setObject:val
                                                      forKey:kUserDefaultsEventVal];
        }
        if (![[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsDailyVal]) {
            NSString* val = @"06:30";
            [[NSUserDefaults standardUserDefaults] setObject:val
                                                      forKey:kUserDefaultsDailyVal];
        }
        //_eventAheadTime = 30;
        //_dailyAlertTime = @"06:30";
    }
    return self;
}

+ (BOOL)isEventAlertOn{
    BOOL isEventAlertOn = YES;
    isEventAlertOn = [[[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsEventAlert] boolValue];
    return isEventAlertOn;
}

+ (void)setEventAlert:(BOOL)on{
    NSNumber* isOn = [NSNumber numberWithBool:on];
    [[NSUserDefaults standardUserDefaults] setObject:isOn
                                              forKey:kUserDefaultsEventAlert];
    NSLog(@"setDailyAlert val is: %@",[[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsDailyAlert]);
}

+ (BOOL)isDailyAlertOn{
    BOOL isDailyAlertOn = YES;
    
    isDailyAlertOn = [[[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsDailyAlert] boolValue];
    return isDailyAlertOn;
}

+ (void)setDailyAlert:(BOOL)on{
    NSNumber* isOn = [NSNumber numberWithBool:on];
    [[NSUserDefaults standardUserDefaults] setObject:isOn
                                              forKey:kUserDefaultsDailyAlert];
    
    NSLog(@"setDailyAlert val is: %@",[[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsDailyAlert]);
}

- (void)reloadData{

    //TODO: 查询所有关注赛事，然后  self.eventsArray = result;
}
- (void)scheduleEventLocalNotification{
    [self clearNotifications];
    if ([AlertService isEventAlertOn]) {
        for (GameEvent* event in self.eventsArray) {
            [self addNotificationForEvent:event];
        }
    }
    
}
- (void)scheduleDailyLocalNotification{
    if (![AlertService isDailyAlertOn]) {
        return;
    }
    NSDate* beginDate = [self beginDate];
    NSDate* endDate = [self endDate];
    NSInteger days = [endDate day] - [beginDate day];
    NSDate* scheduleDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // Find Sunday for the given date
    NSDateComponents *offsetDate = [[NSDateComponents alloc] init];
    
    if ([AlertService isDailyAlertOn]) {
        for (int i = 0; i < days; i++) {
            [offsetDate setDay:i];
            scheduleDate = [calendar dateByAddingComponents:offsetDate
                                                     toDate:beginDate
                                                    options:0];
            //NSInteger numberOfMatch = [[YODataManager sharedManager] numberOfMatchAtDate:scheduleDate];
            //TODO: 查询当天赛事总数
            NSString* alertBody = [NSString stringWithFormat:NSLocalizedString(@"今日共有%d个赛事", nil),1];
            [self addDailyNotificationAt:scheduleDate
                                withInfo:alertBody];
        }
    }
    

}

- (void)addNotificationForEvent:(GameEvent*)event{
    NSLog(@"addNotificationForEvent : %@",event);
    
    if ([event.begintime integerValue] < 1 ) {
        return;
    }
    ;

    NSDate* fireDate = [self fireDateFromDate:[NSDate dateFromString:event.begintime formatted:@"yyyyMMddHHmmss00"]];
    
    // Else, schedule the local notificatoin
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = fireDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    
    localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@赛事即将开始", nil),event.title];
    
    localNotif.alertAction = NSLocalizedString(@"OK", nil);
    
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

}

- (void)addDailyNotificationAt:(NSDate*)date
                      withInfo:(NSString*)text{
    if ([date isLessThan:[NSDate date]] ) {
        return;
    }
    
    NSDate* fireDate = [self fireDateFromDate:date];
    
    // Else, schedule the local notificatoin
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = fireDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    
    localNotif.alertBody = text;
    localNotif.alertAction = NSLocalizedString(@"OK", nil);
    
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    
}

- (void)removeNotification:(NSNotification*)notify{
    [[UIApplication sharedApplication] cancelLocalNotification:(UILocalNotification*)notify];
}

- (void)clearNotifications{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    NSArray* localNotificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    for (UILocalNotification* localNotification in localNotificationArray) {
        [[UIApplication sharedApplication] cancelLocalNotification:localNotification];
    }
}

#pragma mark ()
- (void)setDailyAlertTime:(NSString*)time{
    //_dailyAlertTime = time;
    [[NSUserDefaults standardUserDefaults] setObject:time
                                              forKey:kUserDefaultsDailyVal];
}

- (NSString*)getDailyAlertTime{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsDailyVal];
}

- (void)setEventAheadTime:(NSString*)time{
    [[NSNotificationCenter defaultCenter] postNotificationName:AlertDidChangedNotification
                                                        object:nil];
    [[NSUserDefaults standardUserDefaults] setObject:time
                                              forKey:kUserDefaultsEventVal];
    //_eventAheadTime = time;
}

- (NSString*)getEventAheadTime{
    //NSInteger eventInt = _eventAheadTime;
    //NSString* eventStr = [NSString stringWithFormat:@"%i", eventInt];
    return [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsEventVal];
}

- (NSDate*)beginDate{
    NSInteger hour = [[[[self getDailyAlertTime] componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
    NSInteger minute = [[[[self getDailyAlertTime] componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
    
    NSDate* today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents* component = [calendar components:
                                   NSYearCalendarUnit|
                                   NSMonthCalendarUnit|
                                   NSDayCalendarUnit|
                                   NSHourCalendarUnit|
                                   NSMinuteCalendarUnit
                                              fromDate:today];
    component.hour = hour;
    component.minute = minute;
    NSDate* beginDate = [calendar dateFromComponents:component];
    return beginDate;
}

- (NSDate*)endDate{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString* dateStr = @"2014-08-24 13:20";
    NSDate* date = [formatter dateFromString:dateStr];
    return date;
}

- (NSDate*)fireDateFromDate:(NSDate*)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents* component = [calendar components:
                                   NSYearCalendarUnit|
                                   NSMonthCalendarUnit|
                                   NSDayCalendarUnit|
                                   NSHourCalendarUnit|
                                   NSMinuteCalendarUnit
                                              fromDate:date];
    component.minute -= [[self getEventAheadTime] integerValue];
    NSDate* fireDate = [calendar dateFromComponents:component];
    return fireDate;
}


@end
